<template>
  <el-card id="itemsCard">
    <template #header>
      <!-- 标 题 -->
      <h2>选项管理
        <el-button type="primary" class="btnh2"
        @click="addDrawer=true;pid=''">添加选项</el-button>
      </h2>
    </template>
    <!-- 选项管理信息展示 -->
    <div class="cardDiv">
    <el-tree :default-expand-all="true" :data="items" v-loading="deleteLoading"
    :props="{label: 'itemname', children: 'children'}">
      <template #default="{ data, node }">
        <div>
          <span class="spanTitle">{{data.itemname}}</span>
          <span class="spanEdit">
            <el-button type="primary" class="btn"
            @click.stop="addDrawer=true;pid=data._id">添加子节点</el-button>
            <el-button type="primary" class="btn"
            @click.stop="editShow(data)">编辑</el-button>
            <el-button type="danger" class="btn"
            @click.stop="del(data._id)">删除节点</el-button>
            <el-button type="warning" v-if="node.previousSibling" class="btn"
            @click.stop="sort(data._id, node.previousSibling.data._id)">上移</el-button>
            <el-button type="warning" v-if="node.nextSibling" class="btn"
            @click.stop="sort(data._id, node.nextSibling.data._id)">下移</el-button>
          </span>
        </div>
      </template>
    </el-tree>

    <el-drawer
      title="添加选项"
      size="400px"
      :visible.sync="addDrawer"
      direction="rtl">
      <el-form v-loading="addLoading" style="padding: 10px" :rules="addRules"
      :model="addForm" ref="addForm" label-width="80px">
        <el-form-item label="名称" prop="itemname">
          <el-input v-model="addForm.itemname"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addSave">保存</el-button>
          <el-button @click="addDrawer=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <el-drawer
      title="编辑"
      size="400px"
      :visible.sync="editDrawer"
      direction="rtl">
      <el-form v-loading="editLoading" style="padding: 10px" :rules="editRules"
      :model="editForm" ref="editForm" label-width="80px">
        <el-form-item label="名称" prop="itemname">
          <el-input v-model="editForm.itemname"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="editSave">保存</el-button>
          <el-button @click="editDrawer=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    </div>

  </el-card>
</template>

<script>
import { createNamespacedHelpers } from 'vuex';

const { mapActions, mapState } = createNamespacedHelpers('items');

export default {
  data() {
    // 验证
    const addValidateItemname = async (rule, value, callback) => {
      const { data } = await this.apis.itemsExist({
        field: 'itemname',
        value,
      });
      if (!data) {
        callback();
      } else {
        callback(new Error('选项重复'));
      }
    };
    const editValidateItemname = (rule, value, callback) => {
      if (value === this.row.itemname) {
        callback();
      } else {
        addValidateItemname(rule, value, callback);
      }
    };
    return {
      row: {},
      pid: '',
      deleteLoading: false,
      addLoading: false,
      addDrawer: false,
      addForm: {},
      editLoading: false,
      editDrawer: false,
      editForm: {
        itemname: '',
      },
      addRules: {
        itemname: [
          { required: true, message: '请输入选项', trigger: 'blur' },
          { validator: addValidateItemname, trigger: 'blur' },
        ],
      },
      editRules: {
        itemname: [
          { required: true, message: '请输入选项', trigger: 'blur' },
          { validator: editValidateItemname, trigger: 'blur' },
        ],
      },
    };
  },
  computed: {
    ...mapState(['items']),
  },
  created() {
    this.getItems();
  },
  methods: {
    // 选项节点上下移动排序
    async sort(fid, sid) {
      await this.apis.sortItems(fid, sid);
      this.getItems();
    },
    // 删除选项节点
    del(id) {
      this.$confirm('确定删除吗？').then(async () => {
        this.deleteLoading = true;
        await this.apis.deleteItems(id).catch(() => {
          this.$message('请先删除子节点');
          this.deleteLoading = false;
        });
        this.deleteLoading = false;
        this.getItems();
      }).catch(() => {});
    },
    // 编辑选项节点数据展示
    editShow(data) {
      const { _id: id, itemname } = data;
      this.row = data;
      this.editDrawer = true;
      this.editForm.id = id;
      this.editForm.itemname = itemname;
    },
    // 保存编辑选项节点
    editSave() {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const data = {};
        if (this.editForm.itemname !== this.row.itemname) {
          data.itemname = this.editForm.itemname;
        }
        this.editLoading = true;
        await this.apis.editItems(this.editForm.id, data);
        this.editLoading = false;
        this.editDrawer = false;
        this.getItems();
      });
    },
    // 保存添加选项节点
    addSave() {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const data = {
          itemname: this.addForm.itemname,
        };
        if (this.pid !== '') {
          data.pid = this.pid;
        }
        this.addLoading = true;
        await this.apis.addItems(data);
        this.addLoading = false;
        this.addDrawer = false;
        this.addForm.itemname = '';
        this.getItems();
      });
    },
    ...mapActions(['getItems']),
  },
};
</script>

<style lang="scss" scoped>
  #itemsCard{
    .btnh2{
      width: 80px;
      height: 25px;
      padding: 0;
      text-align: center;
      margin: auto 0;
    }
    .cardDiv{
      width: max-content;
      .spanTitle{
        font-size: 20px;
      }
      .spanEdit{
        padding-left: 10px;
      .btn{
        width: max-content;
        height: 20px;
        padding: 0 5px;
        }
      }
    }
  }
</style>
